﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace myBoard.Framework.Package
{
    public class PackagedFile
    {
        private MemoryStream _packagedFileStream;
        private FileInfo _fileInfo;

        public MemoryStream PackagedFileStream
        {
            get { return _packagedFileStream; }
        }

        ~PackagedFile()
        {
            if(_packagedFileStream!=null)
                _packagedFileStream.Dispose();
        }

        public MemoryStream Pack(string filePath)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException("Specified file does not exist.");
            _fileInfo = new FileInfo(filePath);

            MemoryStream ms = new MemoryStream();
            // First we encode the file header
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); 
            string header = string.Format("{0}{1}{2}", PackageConstants.PACKAGEDFILE_HEADER_START, _fileInfo.FullName, PackageConstants.PACKAGEDFILE_HEADER_END);
            byte[] encodedHeader = encoding.GetBytes(header);
            
            //Then we get the file binaries
            
            int count = 0;
            byte[] buffer = new byte[0x800];
            using (FileStream fs = new FileStream(_fileInfo.FullName, FileMode.Open))
            {
                using (BinaryWriter writer = new BinaryWriter(ms))
                {
                    writer.Write(encodedHeader);
                    writer.Flush();
                    while ((count = fs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        writer.Write(buffer, 0, count);
                        writer.Flush();
                    }
                }
            }

            _packagedFileStream = ms;
            return ms;
        }

        public void UnPack(string destFolder)
        {
            if (!Directory.Exists(destFolder))
                throw new DirectoryNotFoundException(string.Format("Unpack cannot find the specified dest folder : {0}", destFolder));
            
            string destFile = Path.Combine(destFolder, "toto.txt");
            FileStream fs = new FileStream(destFile, FileMode.Create);
            _packagedFileStream.Seek(0, SeekOrigin.Begin);
            byte[] buffer = _packagedFileStream.GetBuffer();
            fs.Write(buffer,0,buffer.Length);
        }

        private PackagedFileHeaderInfo GetHeader()
        {
            if(_packagedFileStream==null)
                return null;
            
            return null;
        }
    }
}
